package com.hedl.classroom.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hedl.classroom.base.exception.CommonError;
import com.hedl.classroom.base.exception.OnlinecClassroomException;
import com.hedl.classroom.config.MultipartSupportConfig;
import com.hedl.classroom.feignclient.MediaServiceClient;
import com.hedl.classroom.mapper.*;
import com.hedl.classroom.model.dto.CourseBaseInfoDto;
import com.hedl.classroom.model.dto.CoursePreviewDto;
import com.hedl.classroom.model.dto.TeachplanDto;
import com.hedl.classroom.model.po.*;
import com.hedl.classroom.service.CourseBaseInfoService;
import com.hedl.classroom.service.CoursePublishService;
import com.hedl.classroom.service.MqMessageService;
import com.hedl.classroom.service.TeachplanService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ProjectName: onlinec-classroom
 * DateTime: 2023/7/23 08:04
 * Author: Big Watermelon
 * Description:
 */
@Slf4j
@Service
public class CoursePublishServiceImpl implements CoursePublishService {

    @Resource
    private CourseBaseInfoService courseBaseInfoService;

    @Resource
    private TeachplanService teachplanService;

    @Resource
    private CourseMarketMapper courseMarketMapper;

    @Resource
    private CoursePublishPreMapper coursePublishPreMapper;

    @Resource
    private CourseBaseMapper courseBaseMapper;

    @Resource
    private CourseTeacherMapper courseTeacherMapper;

    @Resource
    private CoursePublishMapper coursePublishMapper;

    @Resource
    private MqMessageService mqMessageService;

    @Resource
    private MediaServiceClient mediaServiceClient;

    @Override
    public CoursePreviewDto getCoursePreviewInfo(Long courseId) {
        if (courseId == null)
            OnlinecClassroomException.cast("id为空！");
        CoursePreviewDto coursePreviewDto = new CoursePreviewDto();

        //课程基本信息，营销信息
        CourseBaseInfoDto courseBaseInfo = courseBaseInfoService.getCourseBaseInfo(courseId);
        coursePreviewDto.setCourseBase(courseBaseInfo);
        //课程计划信息
        List<TeachplanDto> teachplanDtos = teachplanService.selectTreeNodes(courseId);
        coursePreviewDto.setTeachplans(teachplanDtos);

        return coursePreviewDto;
    }

    @Override
    @Transactional
    public void commitAudit(Long companyId, Long courseId) {
        if (courseId == null || courseId == null)
            OnlinecClassroomException.cast("机构id为空，课程id为空！");
        //查询课程基本信息，营销信息，计划等信息插入到课程预发布表
        CourseBaseInfoDto courseBaseInfo = courseBaseInfoService.getCourseBaseInfo(courseId);
        if (courseBaseInfo == null)
            OnlinecClassroomException.cast("课程找不到！");
        //审核状态
        String auditStatus = courseBaseInfo.getAuditStatus();
        //如果课程的审核状态为已提交则不允许提交
        if (auditStatus.equals("202003"))
            OnlinecClassroomException.cast("课程已提交请等待审核！");
        //课程的图片，计划信息没有填写不允许提交
        String pic = courseBaseInfo.getPic();
        if (StringUtils.isEmpty(pic))
            OnlinecClassroomException.cast("请上传课程图片!");
        //查询课程计划信息
        List<TeachplanDto> teachplanDtos = teachplanService.selectTreeNodes(courseId);
        if (teachplanDtos == null || teachplanDtos.size() == 0)
            OnlinecClassroomException.cast("请编写课程计划！");

        //查询到课程基本信息，营销信息，计划等信息插入到课程预发布表
        CoursePublishPre coursePublishPre = new CoursePublishPre();
        BeanUtils.copyProperties(courseBaseInfo,coursePublishPre);
        //营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        //转json
        String courseMarketJson = JSON.toJSONString(courseMarket);
        coursePublishPre.setMarket(courseMarketJson);
        //计划信息
        String teachplanDtosJson = JSON.toJSONString(teachplanDtos);
        coursePublishPre.setTeachplan(teachplanDtosJson);
        //老师信息
        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseTeacher::getCourseId,courseId);
        List<CourseTeacher> courseTeachers = courseTeacherMapper.selectList(queryWrapper);
        String courseTeachersJson = JSON.toJSONString(courseTeachers);
        coursePublishPre.setTeachers(courseTeachersJson);

        //状态为已提交
        coursePublishPre.setStatus("202003");
        coursePublishPre.setCreateDate(LocalDateTime.now());

        //查询预发布表，如果有记录则更新，没有就插入
        CoursePublishPre coursePublishPreObj = coursePublishPreMapper.selectById(courseId);
        if (coursePublishPreObj == null){
            int insert = coursePublishPreMapper.insert(coursePublishPre);
            if (insert == 0){
                OnlinecClassroomException.cast("插入失败！");
            }
        }else{
            Long companyId1 = coursePublishPreObj.getCompanyId();
            if (companyId1 != companyId){
                OnlinecClassroomException.cast("只能修改自己机构的课程！");
            }
            int update = coursePublishPreMapper.updateById(coursePublishPre);
            if (update == 0)
                OnlinecClassroomException.cast("更新失败！");

        }

        //更新课程基本信息表的审核状态为已提交
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (courseBase == null)
            OnlinecClassroomException.cast("课程更新数据查询失败！");
        courseBase.setAuditStatus("202003");    //审核状态为已提交
        courseBase.setChangeDate(LocalDateTime.now());
        int update = courseBaseMapper.updateById(courseBase);
        if (update == 0)
            OnlinecClassroomException.cast("更新失败！");
    }

    @Override
    @Transactional
    public void publish(Long companyId, Long courseId) {
        if (courseId == null || courseId == null)
            OnlinecClassroomException.cast("机构id为空，课程id为空！");
        //查询程预发布表
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        if (coursePublishPre == null)
            OnlinecClassroomException.cast("课程没有审核记录，无法发布");
        //状态
        String status = coursePublishPre.getStatus();
        //课程没有审核通过不允许发布
        if (!status.equals("202004"))
            OnlinecClassroomException.cast("课程未通过审核，不允许发布！");
        //向课程预发布表写入数据
        CoursePublish coursePublish = new CoursePublish();
        BeanUtils.copyProperties(coursePublishPre,coursePublish);
        CoursePublish coursePublishObj = coursePublishMapper.selectById(courseId);
        //现查询课程发布，如果有则更新，没有在添加
        if (coursePublishObj == null){
            int insert = coursePublishMapper.insert(coursePublish);
            if (insert <= 0)
                OnlinecClassroomException.cast("插入失败！");
        }else{
            int update = coursePublishMapper.updateById(coursePublish);
            if (update <= 0)
                OnlinecClassroomException.cast("更新失败！");
        }

        //向消息表写入数据
        saveCoursePublishMessage(courseId);

        //将预发布表数据删除
        int delete = coursePublishPreMapper.deleteById(courseId);
        if (delete <= 0)
            OnlinecClassroomException.cast("删除失败！");
    }

    @Override
    public File generateCourseHtml(Long courseId) {

        Configuration configuration = new Configuration(Configuration.getVersion());
        //最终的静态文件
        File htmlFile = null;
        try{
            //拿到classpath路径
            URL classpath = this.getClass().getResource("/templates/");

            System.out.println("路径如下："+classpath.getPath());
            //指定模板的目录
            configuration.setDirectoryForTemplateLoading(new File(classpath.getPath()));
            //指定编码
            configuration.setDefaultEncoding("utf-8");
            //的到模板
            Template template = configuration.getTemplate("course_template.ftl");

            //准备数据
            CoursePreviewDto coursePreviewInfo = this.getCoursePreviewInfo(courseId);
            Map<String, Object> map = new HashMap<>();
            map.put("model",coursePreviewInfo);
            //Template template 模板, Object model 数据
            String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);

            //输入流
            InputStream inputStream = IOUtils.toInputStream(html, "utf-8");
            //创建临时文件
            htmlFile = File.createTempFile("coursepublish",".html");

            //输出文件
            FileOutputStream outputStream = new FileOutputStream(htmlFile);
            //使用流将html写入文件
            IOUtils.copy(inputStream,outputStream);
        }catch (Exception e){
            log.error("页面静态化出现问题，课程id：{}",courseId,e);
            e.printStackTrace();
        }
        return htmlFile;
    }

    @Override
    public void uploadCourseHtml(Long courseId, File file) {
        //将file转成 MultipartFile
        MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(file);
        //远程调用得到返回值
        String course = mediaServiceClient.upload(multipartFile, "course", courseId+".html");
        if (course == null){
            log.debug("远程调用走降级逻辑得到上传的结果为null，课程id：{}",courseId);
            OnlinecClassroomException.cast("远程调用媒资服务上传文件失败!");

        }
    }

    /**
     * 根据课程 id查询课程发布信息
     * @param courseId
     * @return
     */
    @Override
    public CoursePublish getCoursePublish(Long courseId) {
        CoursePublish coursePublish = coursePublishMapper.selectById(courseId);
        return coursePublish;
    }

    /**
     * 保存消息表记录
     * @param courseId 课程id
     */
    private void saveCoursePublishMessage(Long courseId){
        MqMessage mqMessage = mqMessageService.addMessage("course_publish",
                String.valueOf(courseId), null, null);
        if (mqMessage == null)
            OnlinecClassroomException.cast(CommonError.UNKOWN_ERROR);
    }
}
